package com.gzzyy.unionchain.communicate.webrtc

import android.util.Log
import com.alibaba.fastjson.JSONObject
import org.webrtc.DataChannel
import org.webrtc.IceCandidate
import org.webrtc.SessionDescription
import java.nio.ByteBuffer
import java.util.*

class WebRtcClient : SignalingClient.SignalingListener {
    private val TAG = WebRtcClient::class.java.simpleName
    private val peers: MutableMap<String, Peer> = HashMap()
    private var client = SignalingClient(this)
    override fun onReceiveSignaling(type: String, fromUid: String, payload: JSONObject?) {
        if (!peers.containsKey(fromUid)) {
            peers[fromUid] = Peer(fromUid, client)
        }
        val peer: Peer? = peers[fromUid]
        when (type) {
            SignalingClient.INIT -> {
                Log.d(TAG, "onReceiveInit fromUid:$fromUid")
                peer?.peerConnection?.createOffer(peer, Peer.constraints)
            }
            SignalingClient.OFFER -> {
                Log.d(TAG, "onReceiveOffer uid:$fromUid data:$payload")
                val sdp = SessionDescription(
                    SessionDescription.Type.fromCanonicalForm(payload!!.getString("type")),
                    payload.getString("sdp")
                )
                peer?.peerConnection?.setRemoteDescription(peer, sdp)
                peer?.peerConnection?.createAnswer(peer, Peer.constraints)
            }
            SignalingClient.ANSWER -> {
                Log.d(TAG, "onReceiveAnswer uid:$fromUid data:$payload")
                val sdp = SessionDescription(
                    SessionDescription.Type.fromCanonicalForm(payload?.getString("type")),
                    payload?.getString("sdp")
                )
                peer?.peerConnection?.setRemoteDescription(peer, sdp)
            }
            SignalingClient.CANDIDATE -> {
                Log.d(TAG, "onReceiveCandidate uid:$fromUid data:$payload")
                if (peer?.peerConnection?.remoteDescription != null) {
                    val candidate = IceCandidate(
                        payload!!.getString("id"),
                        payload.getIntValue("label"),
                        payload.getString("candidate")
                    )
                    peer.peerConnection.addIceCandidate(candidate)
                }
            }
        }
    }

    fun sendToAll(content: String) {
        for (map in peers) {
            val msg = content.toByteArray()
            val buffer = DataChannel.Buffer(ByteBuffer.wrap(msg), false)
            map.value.dataChannel.send(buffer)
        }
    }

    fun sendMsg(to: String, content: String) {
        for (map in peers) {
            if (map.key == to) {
                val msg = content.toByteArray()
                val buffer = DataChannel.Buffer(ByteBuffer.wrap(msg), false)
                map.value.dataChannel.send(buffer)
            }
        }
    }
}